﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jb.Common.Extensions;
using Jb.Domain;
using Jb.Web.ViewModels;
using Jb.Web.Utility;
using AutoMapper;
using System.Drawing;
using System.IO;

namespace Jb.Web.Areas.JobSeeker.Controllers
{
    [Authorize(Roles = "Job Seeker,Admin")]
    public class HomeController : BaseController
    {
		private JbEntities _Context = new JbEntities();
        
		#region Constructors
		public HomeController()
		{
		}

		public HomeController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods

        /// <summary>
        /// Gets Currently Logged in Users Profile for Edit
        /// </summary>
        /// <returns></returns>
        public ActionResult ProfileEdit()
        {
            Jb.Domain.JobSeeker entity = _Context.JobSeekers.Include("Address").FirstOrDefault(P => P.ID == SessionCache.CurrentUser.JobSeekerID);
            
            ///Check for a Blank JobSeeker Object, Created During Registration
            if (entity != null && entity.Name == AppConstants.ValueOf.UNKNOWN)
            {                
                entity.Name = String.Empty;
                entity.DateOfBirth = DateTime.MinValue;
            }

            JobSeekerViewModel viewModel = Mapper.Map<JobSeekerViewModel>(entity);
            return View(viewModel);
        }

        /// <summary>
        /// Saves Currently Logged In JobSeeker's Profile 
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ProfileEdit(JobSeekerViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return View(viewModel);
            }
            Jb.Domain.JobSeeker entity = _Context.JobSeekers.Include("Address").FirstOrDefault(P => P.ID == LoggedInUser.JobSeekerID);
            if (entity != null)
            {
                //DateTime createdOn = entity.CreatedOn;
                //DateTime addressCreatedOn = entity.Address.CreatedOn;
                //System.Guid activationKey = entity.ActivationKey;
                entity = Mapper.Map<JobSeekerViewModel, Jb.Domain.JobSeeker>(viewModel, entity);
                entity.Address = Mapper.Map<AddressViewModel, Address>(viewModel.Address, entity.Address);
                ///Set few properties after mapping
                //entity.CreatedOn = createdOn;
                entity.ModifiedOn = entity.Address.ModifiedOn = DateTime.Now;
                entity.ModifiedBy = entity.Address.ModifiedBy = LoggedInUser.ID;

                //entity.Address.CreatedOn = addressCreatedOn;
                //entity.Address.ModifiedOn = DateTime.Now;
                entity.HasProfileCompleted = HasProfileCompleted(entity);
                //entity.ActivationKey = activationKey;                
                
                _Context.SaveChanges();
                ViewData[AppConstants.ViewDataKeys.SAVED] = true;

                SessionCache.RefreshUserInfo();
            }
            else
                ViewData[AppConstants.ViewDataKeys.SAVED] = false;

            return View(viewModel);
        }

        #region JobSeeker Photo Upload Section

        public ActionResult PhotoList()
        {            
            Jb.Domain.JobSeeker entity = _Context.JobSeekers.Include("Address").FirstOrDefault(P => P.ID == LoggedInUser.JobSeekerID);
            JobSeekerViewModel viewModel = Mapper.Map<JobSeekerViewModel>(entity);
            return View(viewModel);
        }

        /// <summary>
        /// This Action Method is used to upload the Image
        /// </summary>
        /// <param name="jobSeekerPhoto"></param>
        /// <param name="productID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PhotoList(HttpPostedFileBase jobSeekerPhoto, int jobSeekerID)// = 0, int companyLogoID = 0)
        {
            Jb.Domain.JobSeeker jobSeeker = _Context.JobSeekers.FirstOrDefault(P => P.ID == jobSeekerID);
            JobSeekerViewModel jobSeekerViewModel = ViewBag.Company = Mapper.Map<Jb.Domain.JobSeeker, JobSeekerViewModel>(jobSeeker);
            ViewBag.CompanyID = jobSeekerID;

            if (jobSeekerID != base.LoggedInUser.JobSeeker.ID )
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Invalid Request.";
            else if (jobSeekerPhoto == null)
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Please select a Photo for your company.";
            else if (!WebUtil.IsValidImageFile(jobSeekerPhoto))
                ViewData[AppConstants.ViewDataKeys.IMAGE_UPLOAD_ERROR] = "Sorry! Your selected file is not a valid Photo.";
            else
            {
                int w, h;
                String fileName = ImageManager.SaveTempJpeg(jobSeekerPhoto.InputStream, ConfigReader.JobSeekerPhotoAspectRatio, out w, out h);
                ViewBag.WidthHeight = String.Format("{0},{1}", w, h);
                ViewBag.CropBoxImageUrl = ImageManager.GetTempImageUrl(fileName);
                ViewData[AppConstants.ViewDataKeys.ORIGINAL_FILE_NAME] = jobSeekerPhoto.FileName;
            }
            return View(jobSeekerViewModel);
        }

        [HttpPost]
        public ActionResult CropAndSaveImage(JobSeekerViewModel image)
        {
            cropAndSaveImage(image);
            return Json(image);
        }

        /// <summary>
        /// Deletes a Job Seeker Photo from filesystem and Updates Database accordingly.
        /// </summary>
        /// <param name="jobSeekerID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeletePhoto(int jobSeekerID)
        {
            if (LoggedInUser.JobSeeker.ID != jobSeekerID)
                return Json(false);

            var jobSeeker = _Context.JobSeekers.FirstOrDefault(P => P.ID == jobSeekerID);
            if (jobSeeker == null)
                return Json(false);
            else
            {
                ImageManager.DeleteJobSeekerPhoto(jobSeeker.PhotoFile, jobSeekerID);
                jobSeeker.PhotoFile = null;
                _Context.SaveChanges();

                return Json(true);
            }
        }

        #endregion JobSeeker Photo Upload Section

        #endregion Action Methods

        #region Helper Methods
        /// <summary>
        /// Crops an image selected by a rectangle and saves it in the filesystem.
        /// </summary>
        /// <param name="viewModel"></param>
        private void cropAndSaveImage(JobSeekerViewModel viewModel)
        {
            if (base.LoggedInUser.JobSeeker.ID == viewModel.ID)
            {
                Jb.Domain.JobSeeker jobSeeker = _Context.JobSeekers.FirstOrDefault(P => P.ID == viewModel.ID);
                if (jobSeeker != null && !viewModel.PhotoFile.IsNullOrEmpty())
                {
                    String sourceImage = Server.MapPath(viewModel.PhotoFile);
                    if (System.IO.File.Exists(sourceImage))
                    {
                        //Delete Existing Photo from file System, if any
                        if (!jobSeeker.PhotoFile.IsNullOrEmpty())
                        {
                            String existingLogo = Server.MapPath(ImageManager.GetJobSeekerPhotoUrl(jobSeeker.PhotoFile, jobSeeker.ID));
                            if (System.IO.File.Exists(existingLogo))
                                System.IO.File.Delete(existingLogo);
                        }
                        ///Create the Crop area with user selected rectangle
                        String[] coords = viewModel.CropProperty.Split(',');
                        viewModel.Width = (int)coords[2].ToFloat();
                        viewModel.Height = (int)coords[3].ToFloat();
                        Rectangle rectangle = new Rectangle(coords[0].ToInt(), coords[1].ToInt(), viewModel.Width, viewModel.Height);

                        String proposedFileName = Server.MapPath(ImageManager.GetJobSeekerPhotoUrl(viewModel.OriginalFileName, viewModel.ID));
                        proposedFileName = ImageManager.GetNextFileName(proposedFileName);
                        String[] fileNames = ImageManager.SaveThumbnail(sourceImage, proposedFileName, rectangle, jobSeeker.ID, true, ImageFor.JobSeeker);                        
                        
                        ///Delete Original Source Image from the Logo Directory
                        ///Also we can keep this file for future edit but keeping the source will get unnecessary space in the
                        ///server, if user doesn't really using it. If need to change then they have to upload a new Image.                        
                        if (System.IO.File.Exists(fileNames[0]))
                            System.IO.File.Delete(fileNames[0]);

                        ///Rename the file
                        if (System.IO.File.Exists(fileNames[1]))
                        {
                            String newFileName = Path.GetFileName(fileNames[1]).Replace("_Thumb", String.Empty);
                            System.IO.File.Move(fileNames[1], Path.Combine(Path.GetDirectoryName(fileNames[1]), newFileName));
                            jobSeeker.PhotoFile = newFileName;
                        }

                        viewModel.PhotoFile = ImageManager.GetJobSeekerPhotoUrl(jobSeeker.PhotoFile, jobSeeker.ID);
                        LoggedInUser.JobSeeker.PhotoFile = jobSeeker.PhotoFile;

                        _Context.SaveChanges();
                    }
                }
            }
        }

        private bool HasProfileCompleted(Jb.Domain.JobSeeker entity)
        {
            if (entity.Name != AppConstants.ValueOf.UNKNOWN && entity.DateOfBirth > AppConstants.ValueOf.DEFAULT_DATE_OF_BIRTH)
                return true;

            return false;
        }

        #endregion
    }
}


